import 'dart:async';

import 'package:airplay_plus/airplay_plus.dart';
import 'package:flutter/material.dart';

/**
 * @title AirPlay 切换的组件
 */
class AirPlayWidget extends StatefulWidget {
  Widget disConnectWidget;
  Widget connectWidget;

  AirPlayWidget({
    super.key,
    required this.disConnectWidget,
    required this.connectWidget,
  });

  @override
  State<AirPlayWidget> createState() => _AirPlayWidgetState();
}

class _AirPlayWidgetState extends State<AirPlayWidget> {
  final airplayPlusPlugin = AirplayPlus();
  StreamSubscription? sub;
  bool connectStatus = false;

  @override
  void initState() {
    super.initState();

    //
    airplayPlusPlugin.getAirPlayStatus().then((e) {
      connectStatus = e;
      if (!mounted) return;
      setState(() {});
    });

    sub = airplayPlusPlugin.getAirPlayStatusStream().stream.listen((open) {
      connectStatus = open;
      setState(() {});
    });
  }

  @override
  void dispose() {
    sub?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      child: connectStatus ? widget.connectWidget : widget.disConnectWidget,
    );
  }
}
